package com.ohimy.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.ohimy.dao.impl.GroupDao;
import com.ohimy.dao.impl.GroupUserShipDao;
import com.ohimy.dao.impl.MessageDao;
import com.ohimy.dao.impl.UserDao;
import com.ohimy.entity.Group;
import com.ohimy.entity.GroupUserShip;
import com.ohimy.entity.Message;
import com.ohimy.entity.User;

@Service("homeService")
public class HomeService {

	@Resource(name = "messageDao")
	private MessageDao messageDao;

	@Resource(name = "userDao")
	private UserDao userDao;

	@Resource(name = "groupUserShipDao")
	private GroupUserShipDao groupUserShipDao;

	@Resource(name = "groupDao")
	private GroupDao groupDao;

	/**
	 * 得到未读信息数量
	 * 
	 * @return
	 */
	public int getUnreadMsg(Message message) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Message.class);
		criteria.add(Restrictions.eq("toId", message.getToId())).add(
				Restrictions.eq("status", 0));
		return messageDao.findByCriteria(criteria).size();
	}

	/**
	 * 得到新入会员
	 * 
	 * @return
	 */
	public List<User> getNewJoinUser() {
		return userDao.findByCriteria(0, 4, Order.desc("created"));
	}

	/**
	 * 得到群组中会员数量
	 * 
	 * @param groupId
	 * @return
	 */
	public long getMemberNumInGroup(long groupId) {
		DetachedCriteria criteria = DetachedCriteria
				.forClass(GroupUserShip.class);
		criteria.add(Restrictions.eq("group", groupDao.get(groupId)));
		return groupUserShipDao.findByCriteria(criteria).size();
	}

	/**
	 * 得到会员加入的圈子
	 * 
	 * @param id
	 *            会员ID
	 * @return
	 */
	public List<Group> getGroupInHome(long id) {
		List<Group> result = new ArrayList<Group>();
		DetachedCriteria criteria = DetachedCriteria
				.forClass(GroupUserShip.class);
		criteria.add(Restrictions.eq("user", userDao.get(id))).addOrder(
				Order.desc("id"));
		List<GroupUserShip> g_list = groupUserShipDao.findByCriteria(criteria);
		for (GroupUserShip g : g_list) {
			result.add(g.getGroup());
		}
		return result;
	}

	/**
	 * 通过ID返回用户对象
	 * 
	 * @param id
	 * @return
	 */
	public User getUserById(long uid) {
		return userDao.get(uid);
	}

	// ////////////////////////////
	public void setMessageDao(MessageDao messageDao) {
		this.messageDao = messageDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setGroupUserShipDao(GroupUserShipDao groupUserShipDao) {
		this.groupUserShipDao = groupUserShipDao;
	}

	public void setGroupDao(GroupDao groupDao) {
		this.groupDao = groupDao;
	}

}
